var DB = require("../modules/mdb.js").DB;
var User = require("../modules/DBClasses.js").User;
var Query = require("../modules/Query.js").Query;
var cookieName = require("./cookies").cookieName;
var settings  = require("../settings.js");

module.exports = function(req,res,next){
    
    
    res.locals.success = "succenss";
    res.locals.error   = "none error now";


    if(req.cookies[cookieName.userid]){
	console.log("find cookie");
	var db = new DB();
	var query = new Query();    
	query.start("email").eq(req.cookies[cookieName.userid]).done();
	console.log("begin query");
	//find the specified user
	db.findOne(settings.userCollection,query,
		   function(err){
		       console.log(err);
		       res.locals.user = null;
		       res.locals.error = err;
		       return next();
		       
		   },
		   function(doc){
		       //assume the cookie proofed valid
		       // !!!
		       //check password
		       if(!doc){
			   res.locals.user = null;
			   res.clearCookie(cookieName.userid);
		       }
		       else{
			   res.locals.user = new User(doc.real_name,doc.age,
						      doc.email,doc.mobile,"*","*",
						      doc.address,doc.profession,
						      doc.permissions);
		       }
		       return next();
		       
		   });
	
	}
    else{
	res.locals.user = null;
	return next();
    }
}

